<%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*, kines.ct.*, java.text.NumberFormat, java.util.*, java.text.*" errorPage="" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Corrida</title>
<link rel="stylesheet" href="../css/arastyle.css" type="text/css">
<script src="../js/util.js"></script>
<script>
function calendario(obj) {
	window.open('../utils/calendario.jsp?texto='+obj,'calendario','top=200,left=130,width=180,height=136');
}

function calculaEnganche(cual){
	if(cual=="1"){
		document.forma.enganche.value = Math.round( parseFloat(document.forma.engancheP.value/100) * parseFloat(document.forma.saldo.value)*100)/100;
	}else{
		document.forma.engancheP.value = Math.round( parseFloat(document.forma.enganche.value/document.forma.saldo.value) * 100*100)/100;		
	}
}

function agregarEngancheD(){
	centerPopUp('agregaEnganche.jsp', 'EngancheD', 300, 300, 'YES');	
}

function generaCorrida(){
	document.forma.accion.value = "generar";
	document.forma.submit();
}

function guardar(){
	document.forma.accion.value = "guarda";
	document.forma.submit();
}

function cambiarPlan(){
	document.forma.submit();
}
</script>
</head>

<body class="fondo">
<%
String id_bloqueo = request.getParameter("id_bloqueo");
String fechaFirma = request.getParameter("fechaFirma");
String especial = request.getParameter("esEspecial");
String numPlan = request.getParameter("plan")==null?"0":request.getParameter("plan");

Block bloqueo = Block.getData(Integer.parseInt(id_bloqueo));
Quotation cotizacion = bloqueo.getQuotation();
Development desarrollo = Development.getData(cotizacion.getDevelopmentCode());
Prospect prospecto = cotizacion.getProspect();
SalesPerson vendedor = SalesPerson.getData(prospecto.getSalespersonCode());
PreClient preCliente = PreClient.getData(bloqueo.getId());
Terrain lote = cotizacion.getTerrain();
int planTmp = 0;
if(numPlan.equals("0")){
	planTmp = bloqueo.getSalesPlanNumber();
}else{
	planTmp = Integer.parseInt(numPlan.substring(numPlan.lastIndexOf("|")+1, numPlan.length()));	
}

SalesPlan plan = SalesPlan.getData( planTmp, desarrollo.getCode());

ArrayList enganches = session.getAttribute("enganches")==null? new ArrayList(): (ArrayList)session.getAttribute("enganches");
String mes = session.getAttribute("mes")==null? "1": (String)session.getAttribute("mes");

session.setAttribute("enganches", enganches);
session.setAttribute("mes",mes);

double saldo = request.getParameter("saldo")==null||planTmp!=0?lote.getPricePerMeter()*lote.getArea():Double.parseDouble(request.getParameter("saldo"));
double interes = request.getParameter("interes")==null||planTmp!=0?plan.getMonthlyInterest()*100:Double.parseDouble(request.getParameter("interes"));
double enganche = request.getParameter("enganche")==null||planTmp!=0?(plan.getDownPayment()/100.0)*saldo:Double.parseDouble(request.getParameter("enganche"));
double engancheP = request.getParameter("engancheP")==null||planTmp!=0?plan.getDownPayment():Double.parseDouble(request.getParameter("engancheP"));
double descuento = request.getParameter("descuento")==null||planTmp!=0?plan.getCashPayment():Double.parseDouble(request.getParameter("descuento"));
int plazo = request.getParameter("plazo")==null||planTmp!=0?plan.getTerm():Integer.parseInt(request.getParameter("plazo"));
double pago = request.getParameter("pago")==null||planTmp!=0?( (saldo-enganche)*(plan.getMonthlyInterest()/100) )/(1.0-Math.pow((1.0+(plan.getMonthlyInterest()/100)), -plazo)):Double.parseDouble(request.getParameter("pago"));
String tipoPago = request.getParameter("tipo_pago")==null?"1":request.getParameter("tipo_pago");

double engancheFijo = (plan.getDownPayment()/100.0)*(lote.getPricePerMeter()*lote.getArea());
enganche = engancheFijo;
for(int i=0;i<enganches.size(); i++){
	enganche -= Double.parseDouble((String)enganches.get(i));
}

Object [] rows = null;
double engancheT = enganche;
String diferidos = ""+enganche;
String diferidoTmp = "";

if(request.getParameter("accion").equals("generar")){
	for(int i=0;i<enganches.size(); i++){
		diferidoTmp = (String)enganches.get(i);
		engancheT += Double.parseDouble(diferidoTmp);
		diferidos += ","+diferidoTmp;
	}

	try{
		int id_corrida = bloqueo.getCorrida();
		if(id_corrida==0 || planTmp!=bloqueo.getSalesPlanNumber()){
			rows = SalesPlan.corridaPlanEspecial(plazo, interes/10000, plan.getManagementCost(), plan.getInsurance(), saldo, Integer.parseInt(mes), diferidos, engancheT, fechaFirma, Integer.parseInt(tipoPago), pago, descuento);
		}else{
			rows = bloqueo.ejecutaCorrida(id_corrida);
		}
	}catch(Exception e){out.println(e.getMessage());}

} else if(request.getParameter("accion").equals("guarda")){
	try{
		boolean guardo = Corrida.guardaCorrida(Integer.parseInt(id_bloqueo), plazo, interes/10000, plan.getManagementCost(), plan.getInsurance(), saldo, Integer.parseInt(mes), diferidos, engancheT, fechaFirma, Integer.parseInt(tipoPago), pago, descuento);
	%>
		<script> 
			<%if(guardo){%>
				alert('Corrida guardada!');
				window.opener.document.GuardarDatosProspecto.conCorrida.value = "1";
				window.close();
			<%}else{%>
				alert('Error al guardar corrida');
			<%}%>
		</script>
<%		
	}catch(SQLException e){out.println(e);}
	
}

NumberFormat nf = NumberFormat.getInstance();
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);

SimpleDateFormat sdf      = new SimpleDateFormat( "yyyy/MM/dd" );
%>
<form name="forma" method="post" action="configurar_corrida.jsp">
<input name="accion" value="<%=request.getParameter("accion")%>" type="hidden">
<input name="id_bloqueo" value="<%=id_bloqueo%>" type="hidden">
<input name="fechaFirma" value="<%=fechaFirma%>" type="hidden">
<input name="esEspecial" value="<%=especial%>" type="hidden">
<table width="90%" border="0" cellpadding="1" cellspacing="1" bgcolor="#E0E4FE" align="center">
	<tr>
		<td class="etiqueta" align="right">Superficie: </td>
		<td class="textfields" bgcolor="#FFFFFF" align="right">&nbsp;<%=lote.getArea()%></td>
		<td class="etiqueta" align="right">Cliente: </td>
		<%String [] apellidos = preCliente.getLastName();%>
		<td class="textfields" colspan="3" bgcolor="#FFFFFF">&nbsp;<%=preCliente.getFirstName()+" "+apellidos[0]+" "+apellidos[1]%></td>
	</tr>
	<tr>
		<td class="etiqueta" align="right">Precio: </td>
		<td class="textfields" bgcolor="#FFFFFF" align="right">&nbsp;<%=lote.getPricePerMeter()%></td>
		<td class="etiqueta" align="right">Promotor: </td>
		<td class="textfields" colspan="3" bgcolor="#FFFFFF">&nbsp;<%=vendedor.getName()%></td>
	</tr>
	<tr>
		<td class="etiqueta" width="10%" align="right">Monto: </td>
		<td class="textfields" width="15%" bgcolor="#FFFFFF" align="right">&nbsp;<%=saldo%></td>		
		<td class="etiqueta" width="10%" align="right">Desarrollo: </td>		
		<td class="textfields" width="40%" bgcolor="#FFFFFF">&nbsp;<%=desarrollo.getName()%></td>
		<td class="etiqueta" width="10%" align="right">Lote: </td>
		<td class="textfields" width="15%" bgcolor="#FFFFFF">&nbsp;<%=lote.getCode()%></td>
	</tr>
</table>
<br>
<table width="95%" border="0" cellpadding="1" cellspacing="1" bgcolor="#E0E4FE" align="center">
	<tr>
		<td class="titulos" width="20%" align="center">Fecha firma</td>
		<td class="titulos" width="14%" align="center">Interes</td>
		<td class="titulos" width="20%" align="center">Enganche</td>
		<td class="titulos" width="12%" align="center">No.Pagos</td>
		<td class="titulos" width="20%" align="center">Descuento</td>
		<td class="titulos" width="14%" align="center">Pago</td>
	</tr>
</table>
<br>
<table width="95%" border="0" cellpadding="1" cellspacing="1" bgcolor="#E0E4FE" align="center">
	<tr class="titulotabla">
		<td class="txtencabezadotabla" colspan="6" align="center">
			No. plan&nbsp;<select <%=(especial.equals("true")?"disabled":"")%> name="plan" class="textfields" onChange="cambiarPlan(this);">
		  <%
			Object[] planesCotizados = cotizacion.getQuotationSalesPlanAll( );
			for( int i = 0; i < planesCotizados.length; i++ ){
				QuotationSalesPlan planCotizado = (QuotationSalesPlan)planesCotizados[i];
				SalesPlan planT = planCotizado.getSalesPlan( );		

			 %>
			 	<option <%=(Integer.parseInt(numPlan.substring(numPlan.lastIndexOf("|")+1, numPlan.length()))==planT.getNumber()?"selected":"")%> value="<%=planT.getNumber()%>"><%=planT.getNumber()%></option>
			 <%
			}
			 %>
          </select>Plan Normal
			
		</td>		
	</tr>
	<tr>
		<td class="titulosPU" align="center" width="20%"><%=fechaFirma%></td>
		<td class="titulosPU" align="center" width="14%"><%=plan.getMonthlyInterest()*100%></td>
		<td class="titulosPU" align="center" width="20%"><%=nf.format((plan.getDownPayment()/100.0)*(lote.getPricePerMeter()*lote.getArea()))%></td>
		<td class="titulosPU" align="center" width="12%"><%=plan.getTerm()%></td>
		<td class="titulosPU" align="center" width="20%"><%=plan.getCashPayment()%></td>
		<td class="titulosPU" align="center" width="14%"><%=nf.format(( ((lote.getPricePerMeter()*lote.getArea())-(plan.getDownPayment()/100.0)*(lote.getPricePerMeter()*lote.getArea()))*(plan.getMonthlyInterest()/100) )/(1.0-Math.pow((1.0+(plan.getMonthlyInterest()/100)), -plan.getTerm())))%></td>
	</tr>
<%if(especial.equals("true")){%>
	<tr class="titulotabla">
		<td class="txtencabezadotabla" colspan="6" align="center">
			Plan Especial
		</td>		
	</tr>
	<input type="hidden" name="saldo" value="<%=lote.getPricePerMeter()*lote.getArea()%>">
	<tr>
		<td class="titulosPU" width="20%" align="center">
			<input name="fechaFirma" class="textfields" size="10" value="<%=fechaFirma%>">&nbsp;<input type="button" name="boton2" value="#" class="boton" onClick="document.forma.fecha_firma.value = '';calendario('document.forma.fecha_firma');">
		</td>
		<td class="titulosPU" width="14%" align="center"><input name="interes" class="textRigth" align="right" size="5" value="<%=interes%>"></td>
		<td class="titulosPU" width="20%" align="center">
			<a href="javascript: agregarEngancheD();"><img src="../images/icono_desarrollos_precios.gif" border="0" alt="agregar enganches..."></a>
			<input name="engancheP" value="<%=engancheP%>" size="5" class="textRigth" onblur="javascript: calculaEnganche(1);" <%=(enganches.size()>0?" readonly":"")%>>%
			<input name="enganche" class="textRigth" align="right" size="10" value="<%=nf.format(enganche).replaceAll(",","")%>" onblur="javascript: calculaEnganche(2);" <%=(enganches.size()>0?" readonly":"")%>>
		</td>
		<td class="titulosPU" width="12%" align="center"><input name="pagos" class="textRigth" align="right" size="5" value="<%=plazo%>"></td>
		<td class="titulosPU" width="20%" align="center"><input name="descuento" class="textRigth" align="right" size="10" value="<%=descuento%>"></td>
		<td class="titulosPU" width="14%" align="center"><input name="pago" class="textRigth" size="10" value="<%=nf.format(pago).replaceAll(",","")%>"></td>
	</tr>
	<tr>
		<td class="titulosPU" colspan="3" align="right">
			Pago extraordinario: <select name="tipo_pago" class="textRigth">
									<option value="3">Trimestral</option>
									<option value="4">Cuatrimestral</option>
									<option value="6">Semestral</option>
									<option value="12">Anual</option>
								</select>
		</td>
		<td colspan="3" class="titulosPU" align="right"><input name="botonCorrida" class="boton" type="button" value="Generar" onclick="javascript: generaCorrida();"></td>
	</tr>
<%}else{%>
	<input name="saldo" type="hidden" value="<%=lote.getPricePerMeter()*lote.getArea()%>">
	<input name="fechaFirma" type="hidden" value="<%=fechaFirma%>">
	<input name="intereses" type="hidden" value="<%=plan.getMonthlyInterest()*100%>">
	<input name="enganche" type="hidden" value="<%=nf.format((plan.getDownPayment()/100.0)*(lote.getPricePerMeter()*lote.getArea()))%>">
	<input name="pagos" type="hidden" value="<%=plan.getTerm()%>">
	<input name="descuento" type="hidden" value="<%=plan.getCashPayment()%>">
	<input name="pago" type="hidden" value="<%=nf.format(( ((lote.getPricePerMeter()*lote.getArea())-(plan.getDownPayment()/100.0)*(lote.getPricePerMeter()*lote.getArea()))*(plan.getMonthlyInterest()/100) )/(1.0-Math.pow((1.0+(plan.getMonthlyInterest()/100)), -plan.getTerm())))%>">
<%}%>
</table>
<br>
<center><input name="guarda" type="button" class="boton" value="Guardar" onclick="javascript: guardar();"></center>
<br>
<table width="100%" cellpadding="1" cellspacing="1" border="0" align="center" bgcolor="#FFFFFF">
	<tr>
		<td class="titcolumna" align="center" width="5%">No. pago</td>
		<td class="titcolumna" align="center" width="10%">Fecha pago</td>
		<td class="titcolumna" align="center" width="10%">Saldo</td>
		<td class="titcolumna" align="center" width="10%">Pago programado</td>
		<td class="titcolumna" align="center" width="15%">Pago extraordinario</td>
		<td class="titcolumna" align="center" width="10%">Pago total</td>
		<td class="titcolumna" align="center" width="10%">Seguro</td>
		<td class="titcolumna" align="center" width="10%">Gastos Admon.</td>
		<td class="titcolumna" align="center" width="10%">Intereses</td>
		<td class="titcolumna" align="center" width="10%">Capital</td>
	</tr>
	<% if(rows != null){
		int no_pago = 0;
		Calendar fechaPago = null;
		double saldoR = 0;
		double pagoProgramado = 0;
		double pagoExtraordinario = 0;
		double pagoTotal = 0;
		double seguroR = 0;
		double gastosAdmon = 0;
		double intereses = 0;
		double capital = 0;
		
		for(int i=0;i<rows.length;i++){
			Object [] row = (Object []) rows[i];
			no_pago = ((Integer)row[0]).intValue();
			fechaPago = (Calendar)row[1];
			saldoR = ((Double)row[2]).doubleValue();
			pagoProgramado = ((Double)row[3]).doubleValue();
			pagoExtraordinario = ((Double)row[4]).doubleValue();
			pagoTotal = ((Double)row[5]).doubleValue();
			seguroR = ((Double)row[6]).doubleValue();
			gastosAdmon = ((Double)row[7]).doubleValue();
			intereses = ((Double)row[8]).doubleValue();
			capital = ((Double)row[9]).doubleValue();

	%>
			<tr>
				<td class="textcolumna" align="center"><%=no_pago%></td>
				<td class="textcolumna" align="center"><%=sdf.format(fechaPago.getTime())%></td>
				<td class="textcolumna" align="right"><%=nf.format(saldoR)%></td>
				<td class="textcolumna" align="right"><%=nf.format(pagoProgramado)%></td>
				<td class="textcolumna" align="right"><%=nf.format(pagoExtraordinario)%></td>
				<td class="textcolumna" align="right"><%=nf.format(pagoTotal)%></td>
				<td class="textcolumna" align="right"><%=nf.format(seguroR)%></td>
				<td class="textcolumna" align="right"><%=nf.format(gastosAdmon)%></td>
				<td class="textcolumna" align="right"><%=nf.format(intereses)%></td>
				<td class="textcolumna" align="right"><%=nf.format(capital)%></td>
			</tr>
	<%	}
	}%>
</table>
</form>
</body>
</html>